package user

import (
	"context"
	"git.mycaigou.com/gfyx/common/tenant_db"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/constants"
	"gorm.io/gorm"
	"time"
)

type GfyxUserBindRepos struct {
	tenant_db.TenantDB
}

func NewUserBindRepos() GfyxUserBindReposIface {
	return &GfyxUserBindRepos{}
}

func (g *GfyxUserBindRepos) AddUserBind(ctx context.Context, data *GfyxUserBind) error {
	data.CreatedOn = time.Now()
	data.ModifiedOn = time.Now()
	err := g.GetTenantDB(ctx).Create(data).Error
	if err != nil {
		return err
	}
	return nil
}

func (g *GfyxUserBindRepos) SaveUserBind(ctx context.Context, data *GfyxUserBind) error {
	data.CreatedOn = time.Now()
	data.ModifiedOn = time.Now()
	err := g.GetTenantDB(ctx).Save(data).Error
	if err != nil {
		return err
	}
	return nil
}

func (g *GfyxUserBindRepos) GetUserBind(ctx context.Context, userGUID string) (*GfyxUserBind, error) {
	userBind := &GfyxUserBind{}
	err := g.GetTenantDB(ctx).
		Where("user_guid = ?", userGUID).
		Where("is_deleted = ?", constants.IsDeletedFalse).
		Order("created_on desc").First(userBind).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return userBind, err
	}
	return userBind, nil
}

func (g *GfyxUserBindRepos) GetUserBindAll(ctx context.Context) ([]*GfyxUserBind, error) {
	userBind := make([]*GfyxUserBind, 0)
	err := g.GetTenantDB(ctx).
		Where("is_deleted = ?", constants.IsDeletedFalse).
		Order("created_on desc").Find(&userBind).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return userBind, err
	}
	return userBind, nil
}

func (g *GfyxUserBindRepos) UpdateUnionId(ctx context.Context, openId string, userGUID string, unionId string) (bool, error) {
	err := g.GetTenantDB(ctx).
		Table(GfyxUserBind{}.TableName()).
		Where("user_guid=?", userGUID).
		Where("open_id=?", openId).
		Where("is_deleted = ?", constants.IsDeletedFalse).
		Updates(map[string]interface{}{"union_id": unionId}).Error
	if err != nil {
		return false, err
	}
	return true, nil

}
